package vi.org.rongcloud19test;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.sea_monster.exception.BaseException;
import com.sea_monster.exception.InternalException;
import com.sea_monster.network.AbstractHttpRequest;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;
import vi.org.rongcloud19test.Bean.Friends;
import vi.org.rongcloud19test.Bean.Status;
import vi.org.rongcloud19test.Bean.User;
import vi.org.rongcloud19test.activity.BaseApiActivity;
import vi.org.rongcloud19test.activity.ConversationActivity;
import vi.org.rongcloud19test.activity.FriendListActivity;
import vi.org.rongcloud19test.database.UserInfos;
import vi.org.rongcloud19test.utils.Constants;
import vi.org.rongcloud19test.utils.DemoContext;

public class MainActivity extends BaseApiActivity implements View.OnClickListener{

    public static Context mContext;
    private String TAG = "MainActivity";
    private EditText mName,mPwd;
    private Button mLogin;

    private String name,pwd;
    private String Token =
            "zEKUlx9LtouH2XGwjlMDI/Pdk53JowqXe+B/JG20AZngCHT1/lww+oDbHlwaWGySqCn1tNhv0PKAeUsipSf98Q=="
//            "r5yBSmjwuVrmmWgk5KnE2PPdk53JowqXe+B/JG20AZngCHT1/lww+jm5sz+qfmgPgBw2mFMoQowm7WBe+0JkJw=="
            ;
    /*
    request for rong cloud :register login getFriends privateChat
     */
    private AbstractHttpRequest<Status> httpRegisterRequest;
    private AbstractHttpRequest<User> httpLoginRequest;
    private AbstractHttpRequest<User> httpTokenRequest;
    private AbstractHttpRequest<Friends> getUserInfoHttpRequest;

    //通知收到消息的receiver
//    ConversationActivity.PrivateMessageReceiver privateMessageReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = MainActivity.this;
        mName = (EditText)findViewById(R.id.name);
        mPwd = (EditText)findViewById(R.id.pwd);
        mLogin = (Button)findViewById(R.id.login);
        mLogin.setOnClickListener(this);
        /**
         *  设置接收消息的监听器。
         *  需要在connect之前设置。
         */
        RongIM.setOnReceiveMessageListener(new MyReceiveMessageListener());
    }

    public class MyReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {

        /*
         * 收到消息的处理。
         *
         * @param message 收到的消息实体。
         * @param left    剩余未拉取消息数目。
         * @return 收到消息是否处理完成，true 表示走自已的处理方式，false 走融云默认处理方式。
         *
         * 收到消息后通知给conversationAc，进行数据的更新处理。
         */
        @Override
        public boolean onReceived(Message message, int left) {
            Log.i("msg","msgId + targetId + senderId +msg "+"\n" +message.getMessageId()+"+"+
            message.getTargetId()+"+"+message.getSenderUserId()+"+"+((TextMessage)message.getContent()).getContent());
            Intent msgAction = new Intent(Constants.PRIVATE_MSG_RECEIVER);
            msgAction.putExtra(Constants.PRIVATE_MSG_INTENT,message);
            sendBroadcast(msgAction);
            return false;
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.login:
                /*name = mName.getText().toString();
                pwd = mPwd.getText().toString();*/
               /* name = "317461087@qq.com";
                pwd = "123456";*/
                name="491344406@qq.com";
                pwd = "yajie";
                if(name.equals("")&&pwd.equals(""))
                {
                    Log.i(TAG,"name or pwd null");
                }
                else {
                    if (DemoContext.getInstance() != null) {
                        //最后一个参数callback
                        /*httpRegisterRequest = DemoContext.getInstance().getDemoApi().register(name, name,
                                "123", pwd, MainActivity.this);*/
                        /*httpLoginRequest = DemoContext.getInstance().getDemoApi().login(
                                strName,strPwd,MainActivity.this);*/

                        //在服务器拿到的token直接进行注册，登录和获取好友列表操作
                        httpGetTokenSuccess(Token);
                    }
                }
                break;
        }
    }

    @Override
    public void onCallApiSuccess(AbstractHttpRequest request, Object obj) {
        if(httpRegisterRequest != null && httpRegisterRequest.equals(request))
        {
            //注册成功
            registerApiSuccess(obj);
        }
        else if(httpLoginRequest != null && httpLoginRequest.equals(request))
        {
            //登录成功
            loginApiSuccess(obj);
        }
        else if(httpTokenRequest != null && httpTokenRequest.equals(request))
        {
            //成功拿到token后的操作
            getTokenSuccess(obj);
        }
        else if(getUserInfoHttpRequest !=null && getUserInfoHttpRequest.equals(request))
        {
            //成功拿到好友列表
            getFriendsSuccess(obj);
        }
        else{}
    }

    //融云连接和取数据失败的情况如下
    @Override
    public void onCallApiFailure(AbstractHttpRequest request, BaseException e) {
        if(httpRegisterRequest!=null && httpRegisterRequest.equals(request)) {
            Log.e("register : ", e.getMessage());
            if(e instanceof InternalException)
            {
                InternalException ie = (InternalException)e;
                if(ie.getCode() == 403)
                {
                    httpLoginRequest = DemoContext.getInstance().getDemoApi().login(
                            name,pwd,MainActivity.this);
                }
            }
        } else if (httpLoginRequest!=null && httpLoginRequest.equals(request)) {
            Log.e("login: ", "login failed");
            Log.e("register : ", e.getMessage());
        } else if (httpTokenRequest != null && httpTokenRequest.equals(request)) {
            Log.e("token: ", "token failed");
            Log.e("register : ", e.getMessage());
        }
        else if(getUserInfoHttpRequest !=null && getUserInfoHttpRequest.equals(request))
        {
            Log.e("failure: ", "friends failed");
            Log.e("register : ", e.getMessage());
        }
        else {
            Log.e("failure: ","failed");
            Log.e("register : ", e.getMessage());
        }
    }

    private void registerApiSuccess(Object obj)
    {
        if(obj instanceof Status)
        {
            Status status = (Status) obj;
            if(status.getCode() == 200)
            {
                //注册成功的情况，直接登录
                httpLoginRequest = DemoContext.getInstance().getDemoApi().login(
                        name,pwd,MainActivity.this);
            }
            else if(status.getCode() == 101){
                //注册已存在的情况，继续登录
                httpLoginRequest = DemoContext.getInstance().getDemoApi().login(
                        name,pwd,MainActivity.this);
            }
            else {
                //注册失败
                Log.e("register failed","failed");
            }
        }
    }

    private void loginApiSuccess(Object obj)
    {
        //成功登录后获取登录人信息
        if (obj instanceof User) {
            final User user = (User) obj;
            Constants.user = user;
            if (user.getCode() == 200) {
                Constants.loginUser.setUserId(user.getUserId());
                Constants.loginUser.setPortrait(user.getResult().getPortrait());
                if (DemoContext.getInstance() != null && user.getResult() != null) {
                    Log.i("login : ","success");
                    //请求 demo server 获得 token。
//                    httpTokenRequest = DemoContext.getInstance().getDemoApi().getToken(MainActivity.this);

                    //获取好友列表
                    getUserInfoHttpRequest = DemoContext.getInstance().getDemoApi().getFriends(MainActivity.this);
                }
            } else if (user.getCode() == 103) {
                Log.e("login : ","pwd error");
            } else if (user.getCode() == 104) {
                Log.e("login : ","username error");
            }
            else {
                Log.e("login : ","unknown error");
            }
        }
    }
    private void getTokenSuccess(Object obj)
    {
        if (obj instanceof User) {
            final User user = (User) obj;
            if (user.getCode() == 200) {
                if (DemoContext.getInstance() != null && user.getResult() != null) {
                    //获得token，通过token 去做 connect 操作
                    httpGetTokenSuccess(user.getResult().getToken());
                    Log.i("token: ",user.getResult().getToken());
                }
            } else if (user.getCode() == 110) {
                Log.e("token: ","login first please");

            } else if (user.getCode() == 111) {
                Log.e("token: ","cookie is null");
            }
        }
    }

    private void getFriendsSuccess(Object obj)
    {
        //获取好友列表
        if (obj instanceof Friends) {
            final Friends friends = (Friends) obj;
            if (friends.getCode() == 200) {

                for (int i = 0; i < friends.getResult().size(); i++) {
                    UserInfos userInfos = new UserInfos();
                    userInfos.setUserid(friends.getResult().get(i).getId());
                    userInfos.setUsername(friends.getResult().get(i).getUsername());
                    userInfos.setPortrait(friends.getResult().get(i).getPortrait());
//                    Log.i("friends name", friends.getResult().get(i).getUsername());
                    userInfos.setStatus("1");
                    if (friends.getResult().get(i).getPortrait() != null)
                        userInfos.setPortrait(friends.getResult().get(i).getPortrait());
                    Constants.friendsList.add(userInfos);
                }
            }
            else {
                Log.e("err code:",friends.getCode()+"——"+friends.getMessage());
            }
        }
        Intent intent = new Intent(MainActivity.this, FriendListActivity.class);
        startActivity(intent);
        finish();
    }
    /**
     * 融云 第二步：connect 操作
     *
     * @param token
     */
    private void httpGetTokenSuccess(String token) {

        try {
            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                //暂时现在incorrect里面取token
                @Override
                public void onTokenIncorrect() {
                    Log.e("connect: ", "----connect onTokenIncorrect--");

                    /*if (RongIM.getInstance() != null) {
                        RongIM.getInstance().startPrivateChat(MainActivity.this, "82859", "name");
                    }*/
                }

                @Override
                public void onSuccess(String userId) {

                    Log.d("connect: ", "----connect onSuccess userId----:" + userId);
                    //注册接口
                    httpRegisterRequest = DemoContext.getInstance().getDemoApi().register(name, name,
                            "123", pwd, MainActivity.this);
                    /*if (RongIM.getInstance() != null) {
                        RongIM.getInstance().startPrivateChat(MainActivity.this, "82808", "name");
                    }*/
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {

                    Log.e("connect: ", "----connect onError ErrorCode----:" + e);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
